package me.zhengjie.modules.fund.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.base.BaseEntity;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.fund.domain.UserFundFlow;
import me.zhengjie.modules.fund.service.UserFundFlowService;
import me.zhengjie.modules.fund.service.dto.UserFundFlowDto;
import me.zhengjie.modules.fund.service.dto.UserFundFlowQueryCriteria;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Set;

@RestController
@RequestMapping("/api/userfundflow")
@Api(tags = "工具：我的基金操作纪录")
public class UserFundFlowController {

    private static final String ENTITY_NAME = "userFundFlow";

    @Resource
    private UserFundFlowService userFundFlowService;

    @GetMapping
    @ApiOperation("查询我的基金操作日志")
    @PreAuthorize("@el.check('userfundflow:list')")
    public ResponseEntity<Object> query(UserFundFlowQueryCriteria queryCriteria, Pageable pageable) {
        queryCriteria.setUserId(SecurityUtils.getCurrentUserId());
        Page<UserFundFlowDto> pageUserFundFlowDtos = userFundFlowService.queryAll(queryCriteria, pageable);
        return new ResponseEntity<>(PageUtil.toPage(pageUserFundFlowDtos), HttpStatus.OK);
    }

    @PostMapping
    @ApiOperation("新增我的基金操作纪录")
    @PreAuthorize("@el.check('userfundflow:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody UserFundFlow resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        resources.setUserId(SecurityUtils.getCurrentUserId());
        userFundFlowService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @ApiOperation("更新我的基金操作纪录")
    @PreAuthorize("@el.check('userfundflow:edit')")
    public ResponseEntity<Object> update(@Validated(BaseEntity.Update.class) @RequestBody UserFundFlow resources) {
        userFundFlowService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @ApiOperation("删除我的基金操作纪录")
    @PreAuthorize("@el.check('userfundflow:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> deleteIds) {
        userFundFlowService.delete(deleteIds);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
